package com.tiennt.android.apkextractor.utilities;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import android.util.Log;

public class ZipArchiveUtils {
	// http://stackoverflow.com/a/10997886

	/**
	 * All paths must end with slash "/"
	 * 
	 * @param path
	 * @param zipname
	 * @param outputPath
	 * @return
	 */
	public static boolean unZip(String path, String zipname, String outputPath) {

		final int BUFFER_SIZE = 8192;

		BufferedOutputStream bufferedOutputStream = null;
		FileInputStream fileInputStream;
		try {
			fileInputStream = new FileInputStream(path + zipname);
			ZipInputStream zipInputStream = new ZipInputStream(
					new BufferedInputStream(fileInputStream));
			ZipEntry zipEntry;

			while ((zipEntry = zipInputStream.getNextEntry()) != null) {

				String zipEntryName = zipEntry.getName();
				File file = new File(outputPath + zipEntryName);

				if (zipEntry.isDirectory()) {
					Log.v(Config.TAG, zipEntryName + " is a directory");
					file.mkdirs();
				} else {
					Log.v(Config.TAG, zipEntryName + " is not a directory");

					Log.v(Config.TAG,
							"f2 parent: "
									+ file.getParentFile().getPath()
									+ ": "
									+ (file.getParentFile() == null ? "NULL"
											: "NOT NULL")
									+ " --- "
									+ (file.getParentFile().exists() ? "exists"
											: "not exists"));

					if (file.getParentFile() != null
							&& !file.getParentFile().exists()) {
						file.getParentFile().mkdirs();
					}

					byte buffer[] = new byte[BUFFER_SIZE];
					Log.v(Config.TAG, "Writing file: " + file.getPath());
					FileOutputStream fileOutputStream = new FileOutputStream(
							file);
					bufferedOutputStream = new BufferedOutputStream(
							fileOutputStream, BUFFER_SIZE);
					int count;

					while ((count = zipInputStream.read(buffer, 0, BUFFER_SIZE)) != -1) {
						bufferedOutputStream.write(buffer, 0, count);
					}

					bufferedOutputStream.flush();
					bufferedOutputStream.close();
				}
			}
			zipInputStream.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}
		return true;

	}
}
